﻿using System;
using System.Globalization;
using System.Web.UI.WebControls;
using CustomerContactSystem.Core.Infrastructure.Utility;
using CustomerContactSystem.Core.Model;

namespace CustomerContactSystem.WebForms.Enquiries {
    public partial class Create4 : BasePage {
        private Enquiry _enquiry;

        protected void Page_Load(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, true, "id,type")) {
                return;
            }

            GetEnquiry();
            GetCategories();

            if (Request.QueryString["type"] == "ffu") {
                ReferralForm.Visible = true;
                ResponseForm.Visible = false;
                GetUsers();
            }
            else {
                ReferralForm.Visible = false;
                ResponseForm.Visible = true;
            }
        }

        private void GetEnquiry() {
            var enquiryId = int.Parse(Request.QueryString["id"]);
            _enquiry = EnquiryRepository.GetById(enquiryId);
        }

        private void GetCategories() {
            if (_enquiry == null) {
                return;
            }

            var departmentId = _enquiry.Category.Department.Id;
            var department = DepartmentRepository.GetById(departmentId);

            if (department == null) {
                return;
            }

            DepartmentName.Text = department.DepartmentName;
            var categories = EnquiryCategoryRepository.QueryOver()
                .Where(c => c.Department.Id == departmentId && c.AvailableForSelection)
                .OrderBy(c => c.CategoryName).Asc.List();
            BindDropDownList(Categories, categories, "CategoryName", "Id", "--Select--", "0");
            Categories.SelectedIndex =
                Categories.Items.IndexOf(
                    Categories.Items.FindByValue(_enquiry.Category.Id.ToString(CultureInfo.InvariantCulture)));
        }

        private void GetUsers() {
            if (_enquiry == null) {
                return;
            }

            var departmentId = _enquiry.Category.Department.Id;
            var users = UserRepository.QueryOver().Where(u => u.Department.Id == departmentId && u.IsActive).OrderBy(u => u.DisplayName).Asc.List();

            Referees.Items.Clear();
            Referees.Items.Add(new ListItem
                {
                    Value = "0",
                    Text = "--Select--"
                });
            foreach (var user in users) {
                var userItem = new ListItem
                    {
                        Value = user.Id.ToString(CultureInfo.InvariantCulture),
                        Text = user.DisplayName
                    };

                if (user.FirstPointOfContact) {
                    userItem.Text = user.DisplayName + " (Front Line for " + user.Department.DepartmentName + ")";
                }

                Referees.Items.Add(userItem);
            }

            //BindDropDownList(Referees, users, "DisplayName", "Id", "--Select--", "0");
        }

        protected void FinishCreateEnquiryClick(object sender, EventArgs e) {
            if (!IsValidPageRequest(true, false, "id,type")) {
                return;
            }

            GetEnquiry();

            var category = EnquiryCategoryRepository.LoadReference(int.Parse(Categories.SelectedItem.Value));
            _enquiry.Category = category;

            EnquiryClosure closure = null;
            EnquiryReferral referral = null;
            EnquiryFirstReferral firstReferral = null;
            EnquiryCurrentReferral currentReferral = null;

            if (Request.QueryString["type"] == "ffu") {
                var viewUrl = ConfigSettings.SiteRoot + "Enquiries/View.aspx?id=" + _enquiry.Id;
                var referredUser = UserRepository.GetById(int.Parse(Referees.SelectedItem.Value));
                referral = _enquiry.Refer(LoggedUser, referredUser, viewUrl);
                
                firstReferral = new EnquiryFirstReferral
                    {
                        FirstReferredTo = referredUser,
                        FirstReferredToDepartment = referredUser.Department,
                        FirstReferredToGroup = referredUser.UserGroup
                    };

                currentReferral = new EnquiryCurrentReferral
                    {
                        CurrentlyReferredTo = referredUser,
                        CurrentlyReferredToDepartment = referredUser.Department,
                        CurrentlyReferredToGroup = referredUser.UserGroup
                    };
            } else {
                closure = new EnquiryClosure
                    {
                        ClosedBy = LoggedUser,
                        ClosedByDepartment = LoggedUser.Department,
                        ClosedByGroup = LoggedUser.UserGroup,
                        CustomerWasContacted = CustomerWasAnswered.SelectedIndex > 0,
                        CustomerWasContactedBy = CustomerWasAnswered.SelectedItem.Text,
                        DateClosed = _enquiry.DateOfEnquiry,
                        DeadlineMet = true,
                        EnquiryResponse = EnquiryResponse.Text.HtmlStripped().Replace("/n", "<br />")
                    };
            }

            if (referral != null && IsValidObject(referral, FinishCreateResult)) {
                EnquiryFirstReferralRepository.Add(firstReferral);
                EnquiryCurrentReferralRepository.Add(currentReferral);
                
                _enquiry.FirstReferral = firstReferral;
                _enquiry.CurrentReferral = currentReferral;
                
                EnquiryRepository.Update(_enquiry);

                Response.Redirect("~/Enquiries/Create5.aspx?id=" + _enquiry.Id);
            }
            else if (closure != null && IsValidObject(closure, FinishCreateResult)) {
                EnquiryClosureRepository.Add(closure);
                _enquiry.CurrentStatus = "Resolved at First Point of Contact";
                _enquiry.Close(LoggedUser.DisplayName, closure, false);

                EnquiryRepository.Update(_enquiry);

                Response.Redirect("~/Enquiries/Create5.aspx?id=" + _enquiry.Id);
            }
        }
    }
}